package com.niiwoo.civet.user.service.duboo;

import com.alibaba.dubbo.config.annotation.Service;
import com.niiwoo.civet.user.dao.entity.DataStatus;
import com.niiwoo.civet.user.dto.request.DataStatusRequestDTO;
import com.niiwoo.civet.user.dto.response.DataStatusResponseDTO;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.civet.user.service.UserStatusDubboService;
import com.niiwoo.civet.user.service.local.UserStatusService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 用户状态API实现
 */

@Service(version = "1.0.0")
public class UserStatusDubboServiceImpl implements UserStatusDubboService {

    @Autowired
    UserStatusService userStatusService;

    /**
     * 获取用户状态
     *
     * @param userId 用户id
     * @param dataType 数据类型
     */
    @Override
    public DataStatusResponseDTO getByUserIdAndType(String userId, UserDataTypeEnum dataType){
        DataStatus dataStatus= userStatusService.getByUserIdAndType(userId,dataType);
        if (dataStatus == null) {
            return null;
        }

        DataStatusResponseDTO responseDTO = new DataStatusResponseDTO();
        BeanUtils.copyProperties(dataStatus, responseDTO);
        return responseDTO;
    }

    /**
     * 根据用户和类型：保存用户的状态变更
     * 不存在插入，存在更新
     *
     * @param dataStatusDTO
     * @return int
     * @author zzl
     * @date 2017/11/23 15:58
     */
    @Override
    public int saveDataStatusByUserIdAndType(DataStatusRequestDTO dataStatusDTO) {
        DataStatus dataStatus=new DataStatus();
        BeanUtils.copyProperties(dataStatusDTO, dataStatus);
        return userStatusService.saveDataStatusByUserIdAndType(dataStatus);
    }

    /**
     * 根据用户ID查询所有状态
     *
     * @param userId 用户ID
     */
    @Override
    public List<DataStatusResponseDTO> getAllStatusByUserId(String userId) {
        return Optional.ofNullable(userStatusService.getDataStatusByUserId(userId)).map(
                list -> {
                    if (list.isEmpty()) {
                        return null;
                    }
                    List<DataStatusResponseDTO> responseDTOList = new ArrayList<>(list.size());
                    list.forEach(s -> {
                        DataStatusResponseDTO d = new DataStatusResponseDTO();
                        d.setId(s.getId());
                        d.setDataStatus(s.getDataStatus());
                        d.setDataType(s.getDataType());
                        d.setAuthTime(s.getAuthTime());
                        d.setCreateTime(s.getCreateTime());
                        d.setUpdateTime(s.getUpdateTime());
                        responseDTOList.add(d);
                    });
                    return responseDTOList;
                }
        ).orElse(null);
    }

}
